<template>
	<view class="container">
		<view class="content">
			<view v-if="wifiList.length === 0">正在扫描WiFi...</view>
			<view v-else>
				<view v-for="(wifi, index) in wifiList" :key="index" @click="connectWifi(wifi)">
					{{ wifi.SSID }}
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				wifiList: [], // 保存扫描到的WiFi列表
			};
		},
		mounted() {
			const that = this
			wx.startWifi({
				success() {
					// 在页面加载时扫描WiFi
					that.scanWifi();
				}
			})

		},
		methods: {
			// 扫描WiFi
			scanWifi() {
				uni.getWifiList({
					success: (res) => {
						console.log('wifilist', res)
						wx.onGetWifiList(res => {
							console.log('onGetWifiList', res)
							if (res.wifiList.length !== 0) {

								this.wifiList = res.wifiList;
							} else {
								wx.showToast({
									title: '暂无可连接wifi,请重试',
									icon: 'none'
								})
							}
						})

					},
					fail: (err) => {
						console.error('扫描WiFi失败', err);
						uni.showToast({
							title: '扫描WiFi失败,请打开手机扫描开关！'
						})
					},
				});
			},
			// 连接WiFi
			connectWifi(wifi) {
				uni.showModal({
					editable: true,
					success(res) {
						res.content && uni.connectWifi({
							SSID: wifi.SSID,
							BSSID: wifi.BSSID,
							password: res.content, // 输入你的WiFi密码
							success: (res) => {
								uni.showToast({
									title: '连接WiFi成功',
								})
							},
							fail: (err) => {
								uni.showToast({
									title: '连接WiFi失败'
								})
							},
						})
					}
				})
			}
		}
	}
</script>

<style>
	.container {
		flex: 1;
		justify-content: center;
		align-items: center;
	}

	.content {
		margin: 20px;
	}

	/* 样式可以根据需要自行调整 */
</style>